<?php

namespace apiend\modules\statistic\models;

use Yii;
use common\helpers\ArrayHelper;

/**
 * 概况统计面板
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class OverviewStatsModel extends \common\base\Model {

    /**
     * @var array 基础内容项
     */
    public $store_id;

    /**
     * @var array 基础内容项
     */
    public $datetime = [];

    /**
     * @var array 基础内容项
     */
    private $_begintime;

    /**
     * @var array 基础内容项
     */
    private $_endtime;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['datetime'], 'validateDatetime', 'skipOnEmpty' => false],
            [['datetime'], 'safe'],
            [['store_id'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function validateDatetime($attribute) {
        $datetime = (array) $this->$attribute;
        $times = [];
        if (!empty($datetime)) {
            foreach ($datetime as $date) {
                $times[] = Yii::$app->formatter->asTimestamp($date);
            }
        }
        $times[0] = ArrayHelper::getValue($times, 0, strtotime('today'));
        $times[1] = ArrayHelper::getValue($times, 1, time());

        $this->_begintime = strtotime(date('Y-m-d', min($times)) . '00:00:00');
        $this->_endtime = strtotime(date('Y-m-d', max($times)) . '23:59:59');
    }

    /**
     * {@inheritdoc}
     */
    public function getBegintime() {
        return $this->_begintime ?: strtotime('today');
    }

    /**
     * {@inheritdoc}
     */
    public function getEndtime() {
        return $this->_endtime ?: strtotime('today') + 86400 - 1;
    }

    /**
     * {@inheritdoc}
     */
    public function getTimeInterval() {
        return [
            $this->_begintime,
            $this->_endtime,
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getDuration() {
        return abs($this->beginTime - $this->endTime);
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheKeyName($name) {
        return implode('_', [
            get_called_class(),
            date('YmdH', $this->_begintime),
            date('YmdH', $this->_endtime),
            $this->store_id ?: 'all',
            $name
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function search() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'timeInterval'
        ];
    }

}
